// 个性化设置管理工具

/**
 * 默认设置配置
 */
const DEFAULT_SETTINGS = {
  // 通用设置
  general: {
    theme: 'auto', // auto, light, dark
    language: 'zh-CN', // zh-CN, en-US
    soundEnabled: true,
    vibrationEnabled: true,
    animationEnabled: true,
    autoSave: true
  },
  
  // 测试设置
  test: {
    showInstructions: true,
    autoStartNext: false,
    showProgress: true,
    enableHints: true,
    saveHistory: true,
    maxHistoryRecords: 100
  },
  
  // 记忆力测试设置
  memory: {
    defaultDifficulty: 'normal',
    showSequenceProgress: true,
    enableCountdown: true,
    countdownDuration: 3,
    showNumbersAfterError: true
  },
  
  // 反应力测试设置
  reaction: {
    totalRounds: 5,
    enableFalseStartWarning: true,
    showAverageTime: true,
    enablePracticeMode: false
  },
  
  // 黑猩猩测试设置
  chimp: {
    defaultDifficulty: 'normal',
    showNumberTime: 1000,
    enableGridAnimation: true,
    showAccuracyFeedback: true
  },
  
  // 视觉记忆测试设置
  visual: {
    defaultDifficulty: 1,
    gridSize: 4,
    showSequenceDuration: 800,
    enableColorMode: false
  },
  
  // 打字测试设置
  typing: {
    defaultTime: 60,
    defaultDifficulty: 1,
    showWPMRealtime: true,
    showAccuracyRealtime: true,
    enableWordHighlight: true,
    fontSize: 'medium' // small, medium, large
  },
  
  // 通知设置
  notifications: {
    achievementUnlock: true,
    dailyReminder: false,
    reminderTime: '20:00',
    weeklyReport: true,
    sharePrompt: true
  },
  
  // 隐私设置
  privacy: {
    shareData: false,
    allowAnalytics: true,
    saveLocalData: true,
    autoBackup: false
  },
  
  // 显示设置
  display: {
    fontSize: 'medium', // small, medium, large
    contrast: 'normal', // low, normal, high
    colorBlindMode: false,
    reducedMotion: false,
    highContrast: false
  }
}

/**
 * 获取用户设置
 * @param {string} category - 设置分类（可选）
 * @returns {object} 设置对象
 */
export const getSettings = (category = null) => {
  try {
    const stored = uni.getStorageSync('user_settings')
    let settings = stored ? JSON.parse(stored) : {}
    
    // 合并默认设置
    settings = mergeWithDefaults(settings, DEFAULT_SETTINGS)
    
    if (category) {
      return settings[category] || DEFAULT_SETTINGS[category]
    }
    
    return settings
  } catch (error) {
    console.error('获取设置失败:', error)
    return category ? DEFAULT_SETTINGS[category] : DEFAULT_SETTINGS
  }
}

/**
 * 保存用户设置
 * @param {string} category - 设置分类
 * @param {object} newSettings - 新设置
 * @returns {boolean} 是否保存成功
 */
export const saveSettings = (category, newSettings) => {
  try {
    const currentSettings = getSettings()
    
    if (category) {
      currentSettings[category] = {
        ...currentSettings[category],
        ...newSettings
      }
    } else {
      Object.assign(currentSettings, newSettings)
    }
    
    uni.setStorageSync('user_settings', JSON.stringify(currentSettings))
    
    // 触发设置变更事件
    triggerSettingsChange(category, newSettings)
    
    return true
  } catch (error) {
    console.error('保存设置失败:', error)
    return false
  }
}

/**
 * 重置设置到默认值
 * @param {string} category - 设置分类（可选）
 * @returns {boolean} 是否重置成功
 */
export const resetSettings = (category = null) => {
  try {
    if (category) {
      const currentSettings = getSettings()
      currentSettings[category] = { ...DEFAULT_SETTINGS[category] }
      uni.setStorageSync('user_settings', JSON.stringify(currentSettings))
    } else {
      uni.setStorageSync('user_settings', JSON.stringify(DEFAULT_SETTINGS))
    }
    
    return true
  } catch (error) {
    console.error('重置设置失败:', error)
    return false
  }
}

/**
 * 获取特定设置项
 * @param {string} category - 设置分类
 * @param {string} key - 设置键
 * @returns {any} 设置值
 */
export const getSetting = (category, key) => {
  const categorySettings = getSettings(category)
  return categorySettings[key]
}

/**
 * 设置特定设置项
 * @param {string} category - 设置分类
 * @param {string} key - 设置键
 * @param {any} value - 设置值
 * @returns {boolean} 是否设置成功
 */
export const setSetting = (category, key, value) => {
  const categorySettings = getSettings(category)
  categorySettings[key] = value
  return saveSettings(category, categorySettings)
}

/**
 * 切换布尔类型设置
 * @param {string} category - 设置分类
 * @param {string} key - 设置键
 * @returns {boolean} 新的设置值
 */
export const toggleSetting = (category, key) => {
  const currentValue = getSetting(category, key)
  const newValue = !currentValue
  setSetting(category, key, newValue)
  return newValue
}

/**
 * 导出设置
 * @returns {object} 设置数据
 */
export const exportSettings = () => {
  try {
    const settings = getSettings()
    return {
      version: '1.0',
      exportDate: new Date().toISOString(),
      settings
    }
  } catch (error) {
    console.error('导出设置失败:', error)
    return null
  }
}

/**
 * 导入设置
 * @param {object} settingsData - 设置数据
 * @returns {boolean} 是否导入成功
 */
export const importSettings = (settingsData) => {
  try {
    if (!settingsData || !settingsData.settings) {
      throw new Error('无效的设置数据')
    }
    
    const validatedSettings = validateSettings(settingsData.settings)
    uni.setStorageSync('user_settings', JSON.stringify(validatedSettings))
    
    return true
  } catch (error) {
    console.error('导入设置失败:', error)
    return false
  }
}

/**
 * 获取主题设置
 * @returns {string} 主题名称
 */
export const getTheme = () => {
  const theme = getSetting('general', 'theme')
  
  if (theme === 'auto') {
    // 根据系统时间自动切换
    const hour = new Date().getHours()
    return (hour >= 6 && hour < 18) ? 'light' : 'dark'
  }
  
  return theme
}

/**
 * 设置主题
 * @param {string} theme - 主题名称
 * @returns {boolean} 是否设置成功
 */
export const setTheme = (theme) => {
  return setSetting('general', 'theme', theme)
}

/**
 * 获取语言设置
 * @returns {string} 语言代码
 */
export const getLanguage = () => {
  return getSetting('general', 'language')
}

/**
 * 设置语言
 * @param {string} language - 语言代码
 * @returns {boolean} 是否设置成功
 */
export const setLanguage = (language) => {
  return setSetting('general', 'language', language)
}

/**
 * 检查是否启用声音
 * @returns {boolean} 是否启用声音
 */
export const isSoundEnabled = () => {
  return getSetting('general', 'soundEnabled')
}

/**
 * 检查是否启用震动
 * @returns {boolean} 是否启用震动
 */
export const isVibrationEnabled = () => {
  return getSetting('general', 'vibrationEnabled')
}

/**
 * 检查是否启用动画
 * @returns {boolean} 是否启用动画
 */
export const isAnimationEnabled = () => {
  return getSetting('general', 'animationEnabled')
}

/**
 * 获取测试相关设置
 * @param {string} testType - 测试类型
 * @returns {object} 测试设置
 */
export const getTestSettings = (testType) => {
  const testSettings = getSettings('test')
  const specificSettings = getSettings(testType)
  
  return {
    ...testSettings,
    ...specificSettings
  }
}

/**
 * 保存测试设置
 * @param {string} testType - 测试类型
 * @param {object} settings - 设置对象
 * @returns {boolean} 是否保存成功
 */
export const saveTestSettings = (testType, settings) => {
  return saveSettings(testType, settings)
}

/**
 * 获取通知设置
 * @returns {object} 通知设置
 */
export const getNotificationSettings = () => {
  return getSettings('notifications')
}

/**
 * 检查是否应该显示成就通知
 * @returns {boolean} 是否显示成就通知
 */
export const shouldShowAchievementNotification = () => {
  return getSetting('notifications', 'achievementUnlock')
}

/**
 * 检查是否启用每日提醒
 * @returns {boolean} 是否启用每日提醒
 */
export const isDailyReminderEnabled = () => {
  return getSetting('notifications', 'dailyReminder')
}

/**
 * 获取提醒时间
 * @returns {string} 提醒时间
 */
export const getReminderTime = () => {
  return getSetting('notifications', 'reminderTime')
}

/**
 * 获取显示设置
 * @returns {object} 显示设置
 */
export const getDisplaySettings = () => {
  return getSettings('display')
}

/**
 * 获取字体大小
 * @returns {string} 字体大小
 */
export const getFontSize = () => {
  return getSetting('display', 'fontSize')
}

/**
 * 检查是否启用高对比度
 * @returns {boolean} 是否启用高对比度
 */
export const isHighContrastEnabled = () => {
  return getSetting('display', 'highContrast')
}

/**
 * 检查是否启用色盲模式
 * @returns {boolean} 是否启用色盲模式
 */
export const isColorBlindModeEnabled = () => {
  return getSetting('display', 'colorBlindMode')
}

/**
 * 检查是否减少动画
 * @returns {boolean} 是否减少动画
 */
export const isReducedMotionEnabled = () => {
  return getSetting('display', 'reducedMotion')
}

/**
 * 合并默认设置
 * @param {object} userSettings - 用户设置
 * @param {object} defaultSettings - 默认设置
 * @returns {object} 合并后的设置
 */
const mergeWithDefaults = (userSettings, defaultSettings) => {
  const merged = { ...defaultSettings }
  
  Object.keys(userSettings).forEach(category => {
    if (merged[category] && typeof merged[category] === 'object') {
      merged[category] = {
        ...merged[category],
        ...userSettings[category]
      }
    } else {
      merged[category] = userSettings[category]
    }
  })
  
  return merged
}

/**
 * 验证设置数据
 * @param {object} settings - 设置数据
 * @returns {object} 验证后的设置
 */
const validateSettings = (settings) => {
  const validated = { ...DEFAULT_SETTINGS }
  
  Object.keys(settings).forEach(category => {
    if (validated[category] && typeof validated[category] === 'object') {
      Object.keys(settings[category]).forEach(key => {
        if (key in validated[category]) {
          validated[category][key] = settings[category][key]
        }
      })
    }
  })
  
  return validated
}

/**
 * 触发设置变更事件
 * @param {string} category - 设置分类
 * @param {object} newSettings - 新设置
 */
const triggerSettingsChange = (category, newSettings) => {
  // 可以在这里添加设置变更的回调处理
  console.log(`设置已更新: ${category}`, newSettings)
  
  // 如果是主题设置变更，可以立即应用
  if (category === 'general' && 'theme' in newSettings) {
    applyTheme(getTheme())
  }
  
  // 如果是语言设置变更，可以触发语言切换
  if (category === 'general' && 'language' in newSettings) {
    applyLanguage(newSettings.language)
  }
}

/**
 * 应用主题
 * @param {string} theme - 主题名称
 */
const applyTheme = (theme) => {
  // 这里可以添加主题应用逻辑
  console.log(`应用主题: ${theme}`)
}

/**
 * 应用语言
 * @param {string} language - 语言代码
 */
const applyLanguage = (language) => {
  // 这里可以添加语言切换逻辑
  console.log(`切换语言: ${language}`)
}

/**
 * 获取设置选项定义
 * @returns {object} 设置选项
 */
export const getSettingsOptions = () => {
  return {
    theme: [
      { value: 'auto', label: '自动', description: '根据时间自动切换' },
      { value: 'light', label: '浅色', description: '浅色主题' },
      { value: 'dark', label: '深色', description: '深色主题' }
    ],
    language: [
      { value: 'zh-CN', label: '简体中文', description: '中文界面' },
      { value: 'en-US', label: 'English', description: 'English interface' }
    ],
    fontSize: [
      { value: 'small', label: '小', description: '较小的字体' },
      { value: 'medium', label: '中', description: '标准字体大小' },
      { value: 'large', label: '大', description: '较大的字体' }
    ],
    contrast: [
      { value: 'low', label: '低对比度', description: '柔和的颜色对比' },
      { value: 'normal', label: '标准对比度', description: '标准颜色对比' },
      { value: 'high', label: '高对比度', description: '强烈的颜色对比' }
    ],
    difficulty: [
      { value: 'easy', label: '简单', description: '适合初学者' },
      { value: 'normal', label: '普通', description: '标准难度' },
      { value: 'hard', label: '困难', description: '挑战性难度' }
    ],
    testTime: [
      { value: 30, label: '30秒', description: '快速测试' },
      { value: 60, label: '60秒', description: '标准测试' },
      { value: 120, label: '2分钟', description: '长时间测试' }
    ]
  }
}